using System;
using UnityEngine;

public class UserPreferences : MonoBehaviour
{
	private string userPreferencesFile = "/userPreferences.dat";

	private static UserPreferences _instance;

	public PlayerData playerData;

	private DateTime lastRemoteSaveDate = new DateTime(1900, 1, 1);

	public float remoteSaveInterval = 60f;

	public static UserPreferences instance
	{
		get
		{
			return GetInstance();
		}
		private set
		{
			_instance = value;
		}
	}

	private static UserPreferences GetInstance()
	{
		if (_instance == null)
		{
			FindOrCreateInstance();
		}
		return _instance;
	}

	private static void FindOrCreateInstance()
	{
		UserPreferences userPreferences = UnityEngine.Object.FindObjectOfType<UserPreferences>();
		if (userPreferences != null)
		{
			_instance = userPreferences;
		}
		else
		{
			CreateNewUserPreferences();
		}
	}

	private static void CreateNewUserPreferences()
	{
		GameObject utilitiesGameObject = GetUtilitiesGameObject();
		UserPreferences userPreferences = _instance = utilitiesGameObject.AddComponent<UserPreferences>();
	}

	private static GameObject GetUtilitiesGameObject()
	{
		GameObject gameObject = GameObject.Find("Utilities");
		if (gameObject == null)
		{
			gameObject = new GameObject("Utilities");
			UnityEngine.Object.DontDestroyOnLoad(gameObject);
		}
		return gameObject;
	}

	private void Awake()
	{
		UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
		InitializePlayerData();
	}

	public void Load()
	{
		string path = Application.persistentDataPath + userPreferencesFile;
		if (CryptedFileSaver.IsFileExists(path))
		{
			PlayerData playerData = this.playerData = CryptedFileSaver.LoadFileWithBinaryFormater<PlayerData>(path);
			return;
		}
		DebugUtil.Log("User Preferences not exists");
		if (this.playerData == null)
		{
			this.playerData = new PlayerData();
		}
	}

	private void InitializePlayerData()
	{
		Load();
	}

	public void Save()
	{
		UpdateDateOfPlayerDataSave();
		SaveLocal();
		SaveRemote();
	}

	protected void SaveLocal()
	{
		DebugUtil.Log("Saving Preferecens");
		string path = Application.persistentDataPath + userPreferencesFile;
		CryptedFileSaver.SaveFileWithBinaryFormater(path, playerData);
	}

	protected void UpdateDateOfPlayerDataSave()
	{
		playerData.saveDate = DateTime.Now.ToString();
	}

	protected void SaveRemote()
	{
		if (HaveSaveRemotePermission())
		{
			SaveRemotePreferencessData();
		}
	}

	public void SaveRemotePreferencessData()
	{
	}

	private bool HaveSaveRemotePermission()
	{
		DateTime now = DateTime.Now;
		DateTime value = lastRemoteSaveDate.AddSeconds(remoteSaveInterval);
		if (Globals.instance.serverLoggedIn && now.CompareTo(value) >= 0)
		{
			return true;
		}
		return false;
	}

	protected string CreateUserPreferencesJson()
	{
		return null;
	}
}
